package com.haois.mp.database.module.sdk.util;

import com.haois.mp.database.module.common.daomain.SupCity;
import com.haois.mp.database.util.ReadFileUtil;
import com.xxl.job.core.log.XxlJobLogger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by RuiHaoZ on 2018/4/4 23:55
 * https://www.juhe.cn/
 */
public class JuHeUtil {

    public static final String FILE_NAME = "city.json";

    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    private static Logger logger = LoggerFactory.getLogger(JuHeUtil.class);

    public static JSONObject getRequest(String url, Map params) {
        try {
            String result = net(url, params, "GET");
            logger.info("聚合数据查询结果为:" + "\n" + result);
            XxlJobLogger.log("聚合数据查询结果为:" + "\n" + result);
            JSONObject object = JSONObject.fromObject(result);
            if (object.getInt("error_code") != 0) {
                logger.error("聚合数据查询结果返回错误为:" + object.get("error_code") + ":" + object.get("reason"));
            }
            return object;
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlEncode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlEncode(params));
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    //将map型转为请求参数型
    public static String urlEncode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static Map<String, SupCity> getCityJC(String city) {
        Map params = new HashMap<String, SupCity>();
        JSONObject jsonObject = JSONObject.fromObject(city);
        JSONObject resultObject = jsonObject.getJSONObject("result");
        resultObject.forEach((k, v) -> {
            JSONObject j1 = JSONObject.fromObject(v);
            String province = j1.getString("province");
            JSONArray cityArray = j1.getJSONArray("citys");
            for (int i1 = 0; i1 < cityArray.size(); i1++) {
                JSONObject j2 = cityArray.getJSONObject(i1);
                SupCity supCity = new SupCity(
                        j2.getString("city_name"),
                        j2.getString("city_code"),
                        j2.getString("abbr"),
                        j2.getString("engine"),
                        j2.getString("engineno"),
                        j2.getString("classa"),
                        "class",
                        j2.getString("classno"),
                        j2.getString("regist"),
                        j2.getString("registno")
                );
                params.put(province + supCity.getCityName(), supCity);
            }
        });
        return params;
    }

    public static Map<String, String> getCityPlate(String cityJson) {
        Map params = new HashMap<String, String>();
        JSONObject jsonObject = JSONObject.fromObject(cityJson);
        JSONObject resultObject = jsonObject.getJSONObject("result");
        resultObject.forEach((k, v) -> {
            JSONObject j1 = JSONObject.fromObject(v);
            JSONArray cityArray = j1.getJSONArray("citys");
            for (int i1 = 0; i1 < cityArray.size(); i1++) {
                JSONObject j2 = cityArray.getJSONObject(i1);
                String code = j2.getString("code");
                String city = j2.getString("city");
                String province = j2.getString("province");
                String pCode = j2.getString("Pcode");
                params.put(code, province + city);
            }
        });
        return params;
    }

    public static String getCityJc(String plate) {
        String cityJson = ReadFileUtil.readFile(ReadFileUtil.getFilePath(FILE_NAME));
        Map<String, SupCity> stringSupCityMap = getCityJC(cityJson);
        String plateJson = ReadFileUtil.readFile(ReadFileUtil.getFilePath("static/json/test.json"));
        Map<String, String> map = getCityPlate(plateJson);
        String plateCity = map.get(plate.substring(0, 2));
        SupCity supCity = stringSupCityMap.get(plateCity);
        return supCity.getCityCode();
    }

    public static void main(String[] args) {
        String cityJson = ReadFileUtil.readFile(ReadFileUtil.getFilePath(FILE_NAME));
//        Map<String, SupCity> stringSupCityMap = getCityJC(cityJson);
        System.out.println();
        cityJson = ReadFileUtil.readFile(ReadFileUtil.getFilePath("plate.json"));
        Map map = getCityPlate(cityJson);
        System.out.println();
        System.out.println(getCityJc("粤A1212"));
    }

}
